// 导入第三方包
let express = require('express');
let body = require('body-parser');
let cors = require('cors');
// 导入配置文件
let { port } = require('./config/config')
// 导入全局中间件
let { setFile, pathError, getError } = require('./middleware/index')
// 导入路由总表
let router = require('./router/index')
// 导入数据库
let { connect } = require('./gather/mongo')
const { Server } = require("socket.io");
const http = require('http');
// 创建一个服务
let server = express();
// 连接服务器
connect()
// 添加一个开启跨域资源共享
server.use(cors(
    {
        origin: '*',
        methods: ['GET', 'POST', 'PUT', 'DELETE']
    }
))
// 首先需要我们配置静态资源
server.use('/public', express.static('./public/'))
// 配置全局记录的中间件
server.use(setFile)
// 配置post的中间件
server.use(body({ extended: false }))
server.use(body.json())
// 配置接口数据
server.use('/api', router)
// 配置一个地址错误的全局中间件
server.use(pathError)
// 配置一个全局错误的中间件
server.use(getError)
// 监听端口号
server.listen(port, () => {
    console.log(`成功启动该服务器，该服务器的端口号为${port}`)
    console.log(`基本地址为:http://localhost:${port}`)
})
let app = express();
// websocket服务
const Websocket = http.createServer(app);

const io = new Server(Websocket, {
    cors: {
        origin: '*',
        methods: ['GET', 'POST', 'PUT', 'DELETE']
    }
});

io.on('connection', (socket) => {
    console.log('a user connected');

    socket.on('aaa', (msg) => {
        let aaaa = JSON.parse(msg);
        // console.log('message: ' + msg);
        io.emit(aaaa.id, {
            ...aaaa
        }); // 给前端广播接收到的消息
    });
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
});
Websocket.listen(8080, (res) => {
    console.log('websocket server is running on port 8080', 'http://localhost:8080');
});